package com.kmvc.message.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kmvc.message.R;
import com.kmvc.message.encryption.Encryption;
import com.kmvc.message.tools.WebService;

public class LoginActivity extends Activity {

	private String CheckResult = "nodata", BindResult = "nodata", IMSI = "",
			MolNo = "", phonenumber, key = "", yanzheng, yanresult;
	private Handler checkbindhandler = new Handler();
	private Handler addbindhandler = new Handler();
	private Handler yanhandler = new Handler();
	private ProgressDialog progress;
//	private long exitTime = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginpage);
		final EditText inputphone = (EditText)findViewById(R.id.dropdown);
		final EditText inputyanzheng = (EditText)findViewById(R.id.password);
		final Button login=(Button)findViewById(R.id.login);
		final Button getRegistKey=(Button)findViewById(R.id.getRegistKey);
		
		login.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				phonenumber = inputphone.getText().toString();
				yanzheng = inputyanzheng.getText().toString();
				Pattern p = Pattern
						.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(147))\\d{8}$");
				Matcher m = p.matcher(phonenumber);
				if (m.matches()) {
					CheckPhoneAndKey();
				}else {
					String message = "";
					if (!m.matches()) {
						message = "请输入正确的手机号";
					}
					new AlertDialog.Builder(LoginActivity.this)
					.setMessage(message)
					.setPositiveButton(
							"确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(
										DialogInterface dialog,
										int which) {
									showInputDialog();
								}
							}).show().setCancelable(false);
				}
			}});
		
		getRegistKey.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(LoginActivity.this,getRegistKeyActivity.class);
				startActivity(intent);
			}});
		
		try {
			TelephonyManager mTelephonyMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
			IMSI = mTelephonyMgr.getSubscriberId()+"";
			MolNo = mTelephonyMgr.getDeviceId()+"";
		} catch (Exception e) {
			//  
			e.printStackTrace();
		}

		SharedPreferences shp = getSharedPreferences("phonenumber", 0);
		SharedPreferences shp1 = getSharedPreferences("lock_pwd", 0);
		Editor editor = shp.edit();
		editor.putString("IMSI", IMSI);
		editor.putString("MolNo", MolNo);
		editor.commit();
		if (IMSI.equals("")||IMSI.equals("null")) {
			new AlertDialog.Builder(LoginActivity.this)
					.setMessage("抱歉,您的手机不能使用此软件")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									System.exit(0);
								}
							}).show().setCancelable(false);
		} else {
			Intent intt = getIntent();
			String LastAc = "";
			try {
				LastAc = "" + intt.getStringExtra("LastAc");
			} catch (Exception e) {
				e.toString();
				LastAc = "NO";
			}
			if (LastAc.equals("Lock")||shp1.getString("lock_pwd", "").equals("")) {
				showInputDialog();
			} else {
				progress = ProgressDialog.show(this, "请稍候", "读取数据中...", true);
				CheckBind();
			}
		}
	}
	
	protected void CheckPhoneAndKey() {
		//
		progress = ProgressDialog.show(this, "请稍候", "读取数据中...", true);
		progress.setCancelable(true);
		new Thread() {
			public void run() {
				try{
				yanresult = ""
						+ WebService.CheckPhoneAndKey(phonenumber, yanzheng);
				WebService.GetYanZhen(phonenumber, IMSI, MolNo);}
				catch(Exception e)
				{
					yanresult="";
				}
				yanhandler.post(runnablephonekey);
			}
		}.start();

	}
	
	Runnable runnablephonekey = new Runnable() {

		public void run() {
			progress.dismiss();
			if (yanresult.equals("YES")) {
				CallWebservice();
			} else {
				AlertDialog.Builder close = new AlertDialog.Builder(
						LoginActivity.this);
				close.setTitle("提示")
						.setMessage("请检查网络、手机号码、验证码信息是否正确")
						.setCancelable(false)
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										LoginActivity.this.finish();
										System.exit(0);

									}
								}).show();

			}
		}
	};
	
	protected void CallWebservice() {
		progress = ProgressDialog.show(this, "请稍候", "读取数据中...", true);
		new Thread() {
			public void run() {
				BindResult = WebService.AddBind(phonenumber, IMSI, MolNo);
				addbindhandler.post(runnableAddBind);
			}
		}.start();

	}

	@Override
	protected void onDestroy() {
		//
		super.onDestroy();
		this.finish();
	}

	Runnable runnableCB = new Runnable() {
		public void run() {
			progress.dismiss();
			// Log.e("MainActivitynew", CheckResult);

			if (CheckResult.equals("") || CheckResult.equals("NO")
					|| CheckResult.equals("anyType{}")) {
				showInputDialog();
			} else {
				Intent inte = new Intent(LoginActivity.this,
						GesturePWDCreateActivity.class);
				inte.putExtra("PhoneNumber", CheckResult);
				LoginActivity.this.startActivity(inte);
				LoginActivity.this.finish();
			}
		}
	};

	Runnable runnableAddBind = new Runnable() {
		public void run() {
			progress.dismiss();
			Log.e("MainActivitynew", BindResult);
			if (BindResult.equals("绑定成功！")) {
				Intent inte = new Intent(LoginActivity.this,
						GesturePWDCreateActivity.class);
				inte.putExtra("PhoneNumber", phonenumber);
				LoginActivity.this.startActivity(inte);
				LoginActivity.this.finish();
			}
		}
	};

	Runnable runnableyan = new Runnable() {
		public void run() {
			if (!key.equals("null")) {
				SharedPreferences settingSharedPreferences = getSharedPreferences(
						"phonenumber", 0);
				SharedPreferences.Editor mEditor = settingSharedPreferences
						.edit();
				mEditor.putString("key", Encryption.encode(key));
				mEditor.commit();
				Toast.makeText(LoginActivity.this, "验证码生成成功!,请联系管理员获取验证码",
						Toast.LENGTH_LONG).show();
				Toast.makeText(LoginActivity.this, key, Toast.LENGTH_LONG)
						.show();
			} else {
				Toast.makeText(LoginActivity.this, "网络连接失败,请检查网络",
						Toast.LENGTH_LONG).show();
			}
		}
	};

	private void CheckBind() {

		new Thread() {
			public void run() {
				try {
					CheckResult = "" + WebService.CheckBind(IMSI, MolNo);
				} catch (Exception e) {
					e.printStackTrace();
					CheckResult = "";
				}

				checkbindhandler.post(runnableCB);
			}
		}.start();
	}

	protected void showInputDialog() {
	}
	
}
